<?php
session_start();

// 检查用户是否登录
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

// 获取当前用户和群聊名称
$currentUser = $_SESSION['username'];
$groupName = $_GET['group_name'] ?? null;

if (!$groupName) {
    die("未指定群聊！");
}

// 定义文件路径
$userChatFile = __DIR__ . "/user/$currentUser/chats.json";

// 检查用户聊天文件是否存在
if (!file_exists($userChatFile)) {
    die("用户聊天文件不存在！");
}

// 加载用户的聊天记录
$userChats = json_decode(file_get_contents($userChatFile), true);

// 检查 `chats.json` 是否有群聊记录
if (!is_array($userChats)) {
    die("用户聊天记录格式错误！");
}

// 查找群聊是否存在
$chatFound = false;
foreach ($userChats as $index => $chat) {
    if ($chat['name'] === $groupName) {
        $chatFound = true;
        unset($userChats[$index]); // 删除群聊记录
        break;
    }
}

// 如果群聊未找到，提示错误
if (!$chatFound) {
    die("群聊不存在或您未加入此群聊！");
}

// 更新 `chats.json` 文件
file_put_contents($userChatFile, json_encode(array_values($userChats)));

echo "<script>alert('已成功退出群聊！'); location.href='index.php';</script>";
exit();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>退出群聊</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .popup {
            background: white;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            width: 90%;
            max-width: 400px;
        }

        .popup h1 {
            font-size: 18px;
            margin-bottom: 20px;
        }

        .popup button {
            padding: 10px 20px;
            margin: 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }

        .popup .confirm {
            background: #FF6347;
            color: white;
        }

        .popup .cancel {
            background: #ddd;
            color: black;
        }
    </style>
</head>
<body>
    <div class="popup">
        <h1>您确定要退出群聊“<?= htmlspecialchars($groupName) ?>”吗？</h1>
        <form method="POST" style="display:inline;">
            <button class="confirm" type="submit">是</button>
        </form>
        <button class="cancel" onclick="location.href='index.php'">否</button>
    </div>
</body>
</html>